package controller

import (
	"fmt"
	"gdfs-center/api"
	"gdfs-center/conf"
	"gdfs-center/engine"
	"gdfs-center/logcat"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"net/http/httputil"
	"net/url"
	"strconv"
)

//http负载均衡代理
func ProxyHttp(c *gin.Context) {
	s := engine.GetEngine().GetWeightStore()
	if s != nil {
		logcat.GetLog().Info("##url =" + c.Request.URL.Path)
		if c.Request.URL.Path == "/gdfs/api/file/getByteArray" || c.Request.URL.Path == "/gdfs/api/file/getFileBase64" {
			//下载文件处理
			log.Println("####文件中间件处理")
			if s.IsAlive() {
				fileKey := c.Query("fileKey")
				r := api.ApiSearchFile(s.Ip+":"+strconv.FormatUint(s.HttpPort, 10), fileKey)
				if r.Code != "0" { //找不到文件 解析秘钥找原本服务器进行下载
					if len(fileKey) > 32 {
						storeid := fileKey[:32] //找到原本服务器id
						if _, ok := engine.GetEngine().StoreMap[storeid]; ok {
							store := engine.GetEngine().StoreMap[storeid]
							sendproxy(store, c)
						}
						return
					}
				}

			}

		}
		sendproxy(s, c)
		return
	}
	http.Error(c.Writer, "Service not available", http.StatusServiceUnavailable)
}

func sendproxy(s *engine.Storage, c *gin.Context) {
	//转发的url，端口
	var target = ""
	if s.Ip == conf.GetNetAddr() {
		target = "127.0.0.1:" + strconv.FormatUint(s.HttpPort, 10)
	} else {
		target = s.Ip + ":" + strconv.FormatUint(s.HttpPort, 10)
	}

	u := &url.URL{}
	//转发的协议，如果是https，写https.
	logcat.GetLog().Sugar().Info("####Scheme:", c.Request.URL.Scheme, "###target", target, "url =", c.Request.URL, "host=", c.Request.Host)
	u.Scheme = "http"
	u.Host = target
	proxy := httputil.NewSingleHostReverseProxy(u)
	//重写出错回调
	proxy.ErrorHandler = func(rw http.ResponseWriter, req *http.Request, err error) {
		logcat.GetLog().Sugar().Infow("http: proxy error: %v", err)
		ret := fmt.Sprintf("http proxy error %v", err)
		//写到body里
		rw.Write([]byte(ret))
	}
	proxy.ServeHTTP(c.Writer, c.Request)
}
